<template>
    <div class="memberinfo-layout"
         >
        <div class="info-back search-part">
            <el-row :gutter="20">
                <el-col :span="12">
                    <div class="back-icon" @click="back()">
                        <i class="fa fa-arrow-left" aria-hidden="true"></i>
                    </div>
                </el-col>
                <el-col :span="10" class="btns">
                    <el-button type="primary" class="save red-btn" @click="submitForm('ruleForm')">保存</el-button>

                </el-col>
            </el-row>

        </div>
        <div class="info-form">

            <el-form :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">

                <el-row :gutter="20">

                    <el-form-item label="名称：" prop="name"
                                  :rules="[
                              {
                                  required: true,
                                  message: '请输入名称',
                                  trigger: 'change'
                              }
                            ]">
                        <el-input v-model="ruleForm.name"></el-input>
                    </el-form-item>


                    <el-form-item label="权限：" prop="roleRightsName">
                        <el-input v-model="ruleForm.roleRightsName" v-on:focus="selectRights()"></el-input>
                    </el-form-item>

                    <el-form-item label="备注：" prop="remark" class="member-mark">
                        <el-input type="textarea" v-model="ruleForm.remark"></el-input>
                    </el-form-item>


                </el-row>

            </el-form>


        </div>
    </div>
</template>


<script>
    import * as type from '../../../store/types';
    export default {
        data: function () {
            return {
                ruleForm: {},
                rulesRole: {},
                id: '',
                loading: false,
                result: [],
            }
        },

        activated: function () {
            this.$$("#content").scrollTop(0)
            let backInfo = this.$route.params;
            console.log(backInfo)
            this.id = this.$route.query.id;
            if (this.id == undefined) {
                this.id = "";
            }
            //从选择列表进入info
            if (backInfo.flag != undefined) {
              console.log("============从选择列表进入info")
                if (backInfo.flag == 'selectRights') {
                    console.log("==========>selectRights");
                    if(backInfo.info != undefined){
                      this.ruleForm = backInfo.info;
                    }
                    this.$set(this.ruleForm, 'roleRightsName', backInfo.selected.name);
                    this.$set(this.ruleForm, 'roleRightsId', backInfo.selected.id);
                }
                else if (backInfo.flag == 'back') {
                    console.log("==========>back");
                    if(backInfo.info != undefined){
                      this.ruleForm = backInfo.info;
                    }
                }
                else {
                    return;
                }


            }
            // 从自身列表页进入
            else {
              console.log("============从自身列表页进入")
                if (this.$route.query.new ) {
                    console.log("============>新增");
                    this.ruleForm = {
                      name: '',
                      roleRightsName: '',
                      remark: ''
                    };
                    this.imageUrl = '';
                    console.log(this.ruleForm)
                }
                else if(this.id != "") {
                  console.log('sdfsdf')
                    this.loading = true;
                    console.log("/role/" + this.id);
                    var that = this;
                    this.$axioxs.get("/role/" + this.id)
                        .then(function (res) {
                            console.log(JSON.stringify(res.data));
                            console.log(res.data);
                            that.loading = false;
                            that.ruleForm = res.data;

                            console.log(that.ruleForm);


                        })
                        .catch(function (error) {
                            console.log(error);
                            self.$message({
                                showClose: true,
                                type: 'error',
                                message: error,
                                onClose: function () {
                                    that.loading = false;
                                }
                            });
                        });
                }
                else {
                  console.log("=========>chang tab");
                }
            }


        },

        methods: {
            back: function () {
                this.$store.commit(type.CHANGE_INDEX, '/role');
                // this.$destroy();
                this.$router.push({
                    path: '/role',
                });

            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        console.log(this.ruleForm);
                        this.loading = true;
                        let self = this;
                        this.$axioxs({
                            method: 'post',
                            url: '/role/',
                            data: this.ruleForm
                        })
                            .then(function (res) {
                                console.log(JSON.stringify(res.data));
                                self.loading = false;
                                self.back();
                                self.$message({
                                    showClose: true,
                                    type: 'success',
                                    message: "权限修改成功，需重新登录生效",
                                });

                            })
                            .catch(function (error) {
                                console.log(error);
                                self.$message({
                                    showClose: true,
                                    type: 'error',
                                    message: error,
                                    onClose: function () {
                                        self.loading = false;
                                    }
                                });
                            });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },

            selectRights: function () {
                console.log("========>selectRights");
                console.log(this.id);
                console.log(this.ruleForm)
                if (this.ruleForm.roleRightsName) {  //选择仓库时已经有选择的了
                    console.log("=======>roleRightsName")
                    this.csv2IdNames(this.ruleForm.roleRightsId, this.ruleForm.roleRightsName);
                    console.log(this.result);
                    this.currentSelected = this.result;
                } else {
                    this.currentSelected = [];
                }

                console.log(this.currentSelected)

                this.$router.push({
                    name: 'select',
                    path: '/select/list',
                    query: {id: this.id},
                    params: {
                        toFlag: "selectRights",
                        info: this.ruleForm,
                        currentSelected: this.currentSelected,
                        isMultiselect: true,
                        url: "/rights/",
                        backUrl: "/role/info?id=",
                        backUrlName: "r"
                    }
                });

            },

            csv2IdNames: function (ids, names) {
                console.log(">>>>>>>>>>>>>>>>>>>csv2IdNames");
                console.log(ids);
                console.log(names);
                if (!ids || !names) {
                    return [];
                }

                if (typeof ids != "string" || typeof names != "string") {
                    return [];
                }
                var ids_arr = ids.replace(' ', '').split(',');
                var names_arr = names.replace(' ', '').split(',');

                console.log(ids_arr);
                console.log(names_arr);


                if (ids_arr.length !== names_arr.length) {
                    console.log("长度不一样");
                    return [];
                }


                var result = [];

                for (var i = 0; i < ids_arr.length; i++) {
                    var obj = {};
                    obj.id = (ids_arr[i]).trim();
                    obj.remark = (names_arr[i]).trim();
                    result.push(obj);
                }


                console.log(result);

                this.result = result;


            }

        }
    }

</script>
<style scoped>


</style>
